package org.simpleframework.mvc.processor.impl;

import lombok.extern.slf4j.Slf4j;
import org.simpleframework.mvc.RequestProcessorChain;
import org.simpleframework.mvc.processor.RequestProcessor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

/**
 * jsp请求处理器 ,规定jsp需要放在templates目录下才能使用
 *
 * @author: Oliver
 * @time: 2020/12/28/22:54
 */
@Slf4j
public class JspRequestProcessor implements RequestProcessor {
    public static final String JSP_SERVLET = "jsp";
    public static final String JSP_PREFIX_TEMPLATES = "/templates";
    //tomcat默认请求派发器RequestDispatcher的名称
    private RequestDispatcher jspServlet;

    public JspRequestProcessor(ServletContext servletContext) {
        jspServlet = servletContext.getNamedDispatcher(JSP_SERVLET);
        if (null == jspServlet) {
            throw new RuntimeException(" there is no JSP_SERVLET");
        }
        log.info("The default servlet for jsp resource is {}", JSP_SERVLET);
    }


    /**
     * 处理jsp请求 ,请求形式 /templates/../*.jsp
     *
     * @param chain 调用链,用于结果处理参数的组装,以及处理时必要的参数信息传递
     * @return 如果已经处理返回false, 没有处理返回true, 让下一个请求处理器进行处理
     * @throws Exception
     */
    @Override
    public boolean process(RequestProcessorChain chain) throws Exception {

        // 看是否为jsp 是,进行处理,不是则返回true
        if (isJsp(chain.getMethodPath())) {
            jspServlet.forward(chain.getRequest(), chain.getResponse());
            return false;
        }
        return true;
    }

    private boolean isJsp(String path) {
        return path.startsWith(JSP_PREFIX_TEMPLATES);
    }
}
